package com.example.tobebigfe.jsbridge

import android.content.Intent
import android.os.Bundle
import android.webkit.WebSettings.LOAD_NO_CACHE
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import com.example.tobebigfe.R
import com.example.tobebigfe.web.WebManager
import kotlinx.android.synthetic.main.activity_main.*

typealias ActivityResultCallback = (requestCode: Int, resultCode: Int, result: Intent?) -> Boolean

// 提取一个通用的WebActivity
open class WebActivity : AppCompatActivity() {

    private var activityResultCallback: ActivityResultCallback? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        WebView.setWebContentsDebuggingEnabled(true)
        webView.settings.cacheMode = LOAD_NO_CACHE
        webView.settings.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
        webView.settings.javaScriptEnabled = true
        webView.settings.allowFileAccess = true
        webView.settings.allowContentAccess = true
        webView.settings.allowUniversalAccessFromFileURLs = true
        webView.settings.allowFileAccessFromFileURLs = true
        webView.webViewClient = CustomWebViewClient(this)

        // 在加载网页前添加我们的js对象
        webView.addJavascriptInterface(BridgeObject(this, webView), "androidBridge")

        webView.loadUrl(getLoadUrl())

        // 更新离线资源
        WebManager.updateProject(getProjectId())
    }

    open fun getProjectId(): String {
        return intent.getStringExtra("project") ?: ""
    }

    // 提出一个抽象方法，让子类实现加载的url
    open fun getLoadUrl(): String {
        return intent.getStringExtra("url") ?: "about:blank"
    }

    fun startActivityForCallback(intent: Intent, requestCode: Int, callback: ActivityResultCallback) {
        activityResultCallback = callback
        startActivityForResult(intent, requestCode)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        activityResultCallback?.let {
            if (it.invoke(requestCode, resultCode, data)) {
                activityResultCallback = null
            }
        }

    }
}
